
import store from '@/store/index'

function connect() {
  return new Promise((resolve, reject) => {
    const socket = window.io(process.env.VUE_APP_WS_BASE_URL, {
      auth: {
        token: `Bearer ${store.state.user.token}`
      }
    })
    socket.on('connect', data => {
      resolve(socket)
    })
    socket.on('connect_error', () => {
      // eslint-disable-next-line prefer-promise-reject-errors
      reject({
        code: 10400,
        msg: '由于网络问题所以没有连接成功'
      })
    })
  })
}
export async function socket({ data, onProgress }) {
  return new Promise((resolve, reject) => {
    connect().then(socket => {
      // 发送请求
      socket.emit('chat', data)

      socket.on('chat progress', text => {
        onProgress(text)
      })
      socket.on('chat completed', chartId => {
        resolve(chartId)
      })
      socket.on('token expiring soon', token => {
        store.commit('user/setToken', token)
      })
      socket.on('send all chat', () => {
        socket.emit('chat', {
          token: store.state.user.token,
          chat: store.getters.currentChat,
          options: {
            temperature: 0.5
          }
        })
      })
      socket.on('chat error', error => {
        reject(error)
      })
      socket.on('disconnect', () => {
        // eslint-disable-next-line prefer-promise-reject-errors
        reject({
          code: 10404,
          msg: '断开连接'
        })
      })
    }).catch(error => reject(error))
  })
}
